package com.activenetwork.util.jaxb;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class JaxbBindUtil {
	
	/**
	 * Binding the XML to corresponding java class and return the java instance 
	 * representing the root node
	 * 
	 * @param <T>
	 * @param bindingPath
	 * @param xmlFile
	 * @param rootClass the java class binding to the root node type
	 * @return
	 */
	public static <T extends Object> T buildObject(InputStream inputStream, String bindingPath, Class<T> rootClass) {
		
		// Get the root node object from DOM
		Element root = null;
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setNamespaceAware(true);
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(inputStream);
			root = doc.getDocumentElement();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// Unmarshal from root node
		JAXBElement<T> XMLRootNode = null;
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(bindingPath);
			Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
			XMLRootNode = unMarshaller.unmarshal(root, rootClass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return XMLRootNode.getValue();
	}

}
